package com.example.test02mybatisplus.interceptor;

import com.baomidou.mybatisplus.core.MybatisParameterHandler;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxy
 * @Date: 2022/04/24/9:35
 * @Description:
 */
@Intercepts({@Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})})
@Component
public class InsertInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        /*PreparedStatement preparedStatement = (PreparedStatement) args[0];
        ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
        if(!this.checkInsert(parameterHandler)){
            return invocation.proceed();
        }
        Object parameterObject = parameterHandler.getParameterObject();
        String name = "paramAdd";
        //参数是map
        if(parameterObject instanceof Map){
            //paramMap.get获取不到对象抛异常
            try {
                List<Object> list = (List<Object>) ((Map)parameterObject).get("list");
                if(!CollectionUtils.isEmpty(list)){
                    for(Object o:list){
                        Field ageField1 =o.getClass().getDeclaredField("name");
                        ageField1.setAccessible(true);
                        ageField1.set(o, name);
                    }
                }
            }catch (Exception e){

            }finally {
                ((Map)parameterObject).put("name",name);
            }
            //参数是对象
        }else {
            Field ageField = parameterObject.getClass().getDeclaredField("name");
            ageField.setAccessible(true);
            ageField.set(parameterObject, name);
        }*/
        return invocation.proceed();
    }

    private boolean checkInsert(ParameterHandler parameterHandler) throws Throwable {
        Field boundSqlF = parameterHandler.getClass().getDeclaredField("boundSql");
        boundSqlF.setAccessible(true);
        BoundSql boundSql = (BoundSql)boundSqlF.get(parameterHandler);
        String sql = boundSql.getSql();
        String sqlType = sql.substring(0,6);
        return "INSERT".equals(sqlType) || "insert".equals(sqlType);
    }
}
